<template>
  <view class="tn-safe-area-inset-bottom">
    <!-- 导航栏 -->
    <u-navbar title="发动态" :border="true" :autoBack="true" />
    <!-- 提示信息 -->
    <u-toast ref="uToast" />
    <!-- 加载动画 -->
    <u-loading-page :loading="loading" :iconSize="100" />
    <view class="tn-safe-area-inset-bottom">
      <view class="tn-flex tn-flex-row-between tn-flex-col-center tn-margin">
        <view class="tn-flex justify-content-item">
          <view class="tn-text-center" style="border-radius: 100rpx;margin-right: 8rpx;width: 45rpx;height: 45rpx;line-height: 45rpx;">
            <text class="tn-icon-topics tn-color-blue" style="font-size: 40rpx;"></text>
          </view>
          <view class="tn-text-lg tn-padding-right-xs">想说点什么</view>
        </view>
        <view class="justify-content-item tn-text-df tn-color-grey">
          <text class="tn-padding-xs">500字内</text>
          <text class="tn-icon-keyboard-circle"></text>
        </view>
      </view>
      <view class="tn-margin tn-bg-gray--light tn-padding" style="border-radius: 10rpx;">
        <textarea v-model="content" maxlength="500" placeholder="说点什么 , 万一火了呢"
          placeholder-style="color:#AAAAAA"></textarea>
      </view>
      <view class="tn-flex tn-flex-row-between tn-flex-col-center tn-margin">
        <view class="tn-flex justify-content-item">
          <view class="tn-text-center" style="border-radius: 100rpx;margin-right: 8rpx;width: 45rpx;height: 45rpx;line-height: 45rpx;">
            <text class="tn-icon-image tn-color-blue" style="font-size: 40rpx;"></text>
          </view>
          <view class="tn-text-lg tn-padding-right-xs">发点什么图咧</view>
        </view>
        <view class="justify-content-item tn-text-df tn-color-grey" @click="clearPic">
          <text class="tn-padding-xs">清空上传</text>
          <text class="tn-icon-delete"></text>
        </view>
      </view>
      <view class="tn-margin-left tn-padding-top-xs">
        <u-upload :capture="['album']" :fileList="fileList" :maxCount="9" :multiple="true" :max-size="1024 * 1024 * 2" @afterRead="afterRead" @delete="deletePic" />
      </view>
      <view class="tn-flex tn-flex-row-between tn-flex-col-center tn-margin tn-padding-bottom tn-padding-top">
        <view class="tn-flex justify-content-item">
          <view class="tn-text-center" style="border-radius: 100rpx;margin-right: 8rpx;width: 45rpx;height: 45rpx;line-height: 45rpx;">
            <text class="tn-icon-discover-planet tn-color-blue" style="font-size: 40rpx;"></text>
          </view>
          <view class="tn-text-lg tn-padding-right-xs">选择圈子</view>
        </view>
        <view class="justify-content-item tn-text-df tn-color-grey" @click="showCicle = true">
          <text class="tn-padding-xs">{{ circleText }}</text>
          <text class="tn-icon-right"></text>
        </view>
      </view>
      <view class="tn-flex tn-flex-row-between tn-flex-col-center tn-margin">
        <view class="tn-flex justify-content-item">
          <view class="tn-text-center" style="border-radius: 100rpx;margin-right: 8rpx;width: 45rpx;height: 45rpx;line-height: 45rpx;">
            <text class="tn-icon-tag tn-color-blue" style="font-size: 40rpx;"></text>
          </view>
          <view class="tn-text-lg tn-padding-right-xs">话题标签</view>
        </view>
      </view>
      <view class="tn-tag-content tn-margin tn-text-justify tn-padding-bottom">
        <view class="topic-box">
          <view class="topic-item" v-for="(item, index) in topic" :key="index">
            <u-tag :text="`#${item.name}`" shape="circle" :plain="!item.checked" :type="item.type ? item.type : 'default'" :name="item.id" @click="checkboxTopic" />
          </view>
        </view>
      </view>
      <!-- 悬浮按钮-->
      <view class="tn-flex tn-footerfixed">
        <view class="tn-flex-1 justify-content-item tn-margin-sm tn-text-center">
          <tn-button backgroundColor="#00FFC6" padding="40rpx 0" width="60%" shadow fontBold @click="publish">
            <text class="tn-icon-camera tn-padding-left-xs tn-color-black"></text>
            <text class="tn-color-black">发 布</text>
          </tn-button>
        </view>
      </view>
    </view>
    <view class='tn-tabbar-height'></view>
    <u-picker :show="showCicle" :columns="[columns]" title="选择圈子" keyName="name" @cancel="showCicle = false" @confirm="checkCircle" />
  </view>
</template>

<script>
import { getDict, getMyCircle, publish, cosToken } from '@/api'
export default {
  name: 'article',
  data() {
    return {
      loading: false,
      showCicle: false,
      fileList: [],
      columns: [],
      topic: [],
      topics: [],
      content: '',
      circleText: '选择',
      circleId: null,
    }
  },

  onLoad() {
    this.init();
  },

  methods: {
    // 初始化
    async init() {
      this.topic = await this.getDict();
      this.columns = await this.getMyCircle();
      this.loading = false;
    },

    // 获取字典
    async getDict() {
      const { code, message, data } = await getDict({ types: 'topic' });
      if (code !== 1000) {
        return this.$refs.uToast.show({
          type: 'error',
          message: message
        });
      }
      return data['topic'];
    },

    // 我的圈子
    async getMyCircle() {
      const { code, message, data } = await getMyCircle();
      if (code !== 1000) {
        return this.$refs.uToast.show({
          type: 'error',
          message: message
        });
      }
      return data;
    },

    // 发动态
    async publish() {
      const { content, circleId, topics, fileList } = this;
      if (!content) {
        return this.$refs.uToast.show({
          type: 'error',
          message: '请输入内容'
        });
      }
      if (!circleId) {
        return this.$refs.uToast.show({
          type: 'error',
          message: '请选择圈子'
        });
      }
      if (!topics.length) {
        return this.$refs.uToast.show({
          type: 'error',
          message: '请选择话题标签'
        });
      }
      console.log(content, circleId, topics, fileList);
      if (fileList.length) {
        const token = await cosToken();
        if (token.code !== 1000) {
          return this.$refs.uToast.show({
            type: 'error',
            message: token.message
          });
        }
        const images = await uni.$u.uploadFile(fileList, token.data);
        const { code, message, data } = await publish({ content, images, circleId, tagIds: topics });
        if (code !== 1000) {
          return this.$refs.uToast.show({
            type: 'error',
            message: message
          });
        }
        this.$refs.uToast.show({
          type: 'success',
          message: message
        });
        setTimeout(() => {
          uni.navigateBack();
        }, 1000);
      } else {
        const { code, message, data } = await publish({ content, images: [], circleId, tagIds: topics });
        if (code !== 1000) {
          return this.$refs.uToast.show({
            type: 'error',
            message: message
          });
        }
        this.$refs.uToast.show({
          type: 'success',
          message: message
        });
        setTimeout(() => {
          uni.navigateBack();
        }, 1000);
      }
    },

    // 选择圈子
    checkCircle(e) {
      this.circleId = e.values[0][0]['id'];
      this.circleText = e.values[0][0]['name'];
      this.showCicle = false;
    },

    // 选择标签
    checkboxTopic(e) {
      const types = ['primary', 'success', 'warning', 'error'];
      const index = Math.floor(Math.random() * types.length);
      this.topic = this.topic.map(item => {
        if (item.id === e && !item.checked) {
          if (this.topics.length < 3) {
            item.checked = true;
            item.type = types[index];
            this.topics.push(e);
          } else {
            this.$refs.uToast.show({
              type: 'error',
              message: '最多选择3个标签'
            });
          }
        } else if (item.id === e && item.checked) {
          item.checked = false;
          item.type = 'default';
          this.topics = this.topics.filter(item => item !== e);
        }
        return item;
      });
    },

    // 读取图片
    afterRead(e) {
      // 如果fileList有数据，追加数据，否则直接赋值
      if (this.fileList.length) {
        this.fileList = this.fileList.concat(e.file);
      } else {
        this.fileList = e.file;
      }
    },

    // 删除图片
    deletePic(e) {
      const that = this;
      uni.showModal({
        title: '温馨提示',
        content: '是否删除该图片',
        success: function (res) {
          if (res.confirm) {
            that.fileList = that.fileList.filter((item, i) => i !== e.index);
          }
        }
      });
    },

    // 清空图片
    clearPic() {
      this.fileList = [];
    }
  }
}
</script>

<style lang="scss" scoped>
.topic-box {
  text-align: start;

  .topic-item {
    display: inline-block;
    margin: 3rpx
  }
}

.tn-tabbar-height {
  height: (env(safe-area-inset-bottom) / 2);
}

.tn-footerfixed {
  position: fixed;
  width: 100%;
  bottom: calc(30rpx + env(safe-area-inset-bottom));
  z-index: 98;
  box-shadow: 0 1rpx 6rpx rgba(0, 0, 0, 0);

}
</style>